package com.cjk.console.ctrl.sys;

import java.security.MessageDigest;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjk.console.SessionApi;
import com.cjk.console.model.LoginInfo;
import com.cjk.console.service.AuthService;
import com.cjk.foundation.commons.BusinessException;
import com.cjk.foundation.commons.response.PageResponse;
import com.cjk.foundation.commons.response.Response;
import com.cjk.foundation.dao.EmployeeDao;
import com.cjk.foundation.entity.EmployeeEntity;
import com.cjk.foundation.util.PasswordUtil;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
	
	@Autowired
	private EmployeeDao employeeDao;
	
	@Autowired
	private AuthService authService;
	
	@RequestMapping(value = "/getEmployeeList.do", method = RequestMethod.POST)
	@ResponseBody
	public PageResponse getEmployeeList(Integer page, Integer pageSize){
		return authService.getEmployeeList(page, pageSize);
	}
	
	@RequestMapping(value = "/saveEmployee.do", method = RequestMethod.POST)
	@ResponseBody
	public Response saveEmployee(Integer id, String username, String password, Integer roleId){
		authService.saveEmployee(id, username, password, roleId);
		return Response.success();
	}
	
	@RequestMapping(value = "/getEmployeeInfo.do", method = RequestMethod.POST)
	@ResponseBody
	public Response getEmployeeInfo(Integer id){
		return Response.success(employeeDao.selectById(id));
	}
	
	@RequestMapping(value = "/delEmployee.do", method = RequestMethod.POST)
	@ResponseBody
	public Response delEmployee(Integer id){
		employeeDao.delete(id);
		return Response.success();
	}
	
	@RequestMapping(value = "/modifyPwd.do", method = RequestMethod.POST)
	@ResponseBody
	public Response modifyPwd(HttpSession session, String newPwd, String oldPwd, String salt){
		final LoginInfo loginInfo = SessionApi.getLoginUserInfo(session);
		EmployeeEntity employeeEntity = employeeDao.selectByUsername(loginInfo.getUsername());
		if(employeeEntity == null){
			throw new BusinessException("用户不存在");
		}
		byte[] pwd = PasswordUtil.encrypt(salt.getBytes(), employeeEntity.getPassword());
		if(!MessageDigest.isEqual(PasswordUtil.hexStringToBytes(oldPwd), pwd)){
			throw new BusinessException("密码错误");
		}
		employeeDao.update(loginInfo.getId(), PasswordUtil.hexStringToBytes(newPwd), null);
		return Response.success();
	}
}
